<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <h2>系统登录</h2>
        </div>
      </template>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="用户名">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="密码" @keydown="keyDown">
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" style="width: 100%">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref } from 'vue'
  import { useRouter } from 'vue-router'
  import type { FormInstance } from 'element-plus'

  const router = useRouter()
  const loginFormRef = ref<FormInstance>()

  const loginForm = reactive({
    username: '',
    password: '',
  })

  const rules = {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  }

  const handleLogin = async () => {
    if (!loginFormRef.value) return
    await loginFormRef.value.validate((valid) => {
      if (valid) {
        // 这里模拟登录成功
        localStorage.setItem('token', 'dummy-token')
        router.push('/home')
      }
    })
  }
  const keyDown = (e) => {
    if (e.keyCode === 13) handleLogin()
  }
</script>

<style lang="scss" scoped>
  .login-container {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f5f7fa;

    .login-card {
      width: 400px;

      .card-header {
        text-align: center;

        h2 {
          margin: 0;
          color: #303133;
        }
      }
    }
  }
</style>
